import { BASE_URL } from "../../utils/config";
interface Course {
    id: string
    courseName: string
}

Page({
  data: {
    leaveList: [] as any[],
    courses: [] as Course[]
  },
  onLoad() {
    this.fetchLeaveList();
    this.fetchCourseList();
  },

  onPullDownRefresh() {
    this.fetchLeaveList().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  async fetchLeaveList() {

    const token = wx.getStorageSync('token')
    wx.request({
      url: `${BASE_URL}/leave/list`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`
      },
      data: {
      },
      success: (res: any) => {
        const { data } = res.data
        if (data) {
          // 将请假记录的courseId匹配对应的课程名称
          const leaveListWithCourseName = data.map((item: any) => {
            const course = this.data.courses.find(course => course.id === item.courseId)
            return {
              ...item,
              courseName: course ? course.courseName : '未知课程'
            }
          })
          this.setData({
            leaveList: leaveListWithCourseName
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取请假列表失败',
          icon: 'error'
        })
      }
    })
  },

  toggleDetail(e: WechatMiniprogram.TouchEvent) {
    const index = e.currentTarget.dataset.index;
    const leaveList = this.data.leaveList;
    leaveList[index].showDetail = !leaveList[index].showDetail;

    this.setData({
      leaveList
    });
  },

  previewImage(e: WechatMiniprogram.TouchEvent) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      urls: [url],
      current: url
    });
  },
  fetchCourseList() {
    const token = wx.getStorageSync('token')
    wx.request({
      url: `${BASE_URL}/course/list`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`
      },
      data: {
      },
      success: (res: any) => {
        const { data } = res.data
        if (data) {
          this.setData({
            courses: data
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取课程列表失败',
          icon: 'error'
        })
      }
    })
  },
});